package xjh.him.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.xjh.him.R;

import xjh.him.common.SharedData;
import xjh.him.entity.User;
import xjh.him.netty.codec.Packet;
import xjh.him.netty.dto.UserDto;
import xjh.him.util.ToastUtil;

public class SearchActivity extends Activity {
    private EditText searchInput;
    private TextView searchInfo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        onBackClick();
        onSearchBtnClick();
    }

    private void onBackClick() {
        ImageView backIcon = findViewById(R.id.search_back_icon);
        backIcon.setOnClickListener((view) -> finish());
    }

    private void onSearchBtnClick() {
        Button searchBtn = findViewById(R.id.search_btn);
        searchInput = findViewById(R.id.search_input);
        searchInfo = findViewById(R.id.search_info);
        searchBtn.setOnClickListener((view) -> {
            String str = searchInput.getText().toString();
            if (str.length() != 11) {
                ToastUtil.show(this, "手机号格式错误");
                return;
            }
            UserDto.SelectByPhoneReq req = new UserDto.SelectByPhoneReq();
            req.setPhone(str);
            SharedData.client.sendMsg(Packet.create(UserDto.SelectByPhoneReq.class, req));
            Object obj = SharedData.future.get();
            if (obj instanceof UserDto.SelectByPhoneResp) {
                UserDto.SelectByPhoneResp resp = (UserDto.SelectByPhoneResp) obj;
                if (resp.getUser() == null) {
                    searchInfo.setText("用户不存在！");
                }else {
                    searchInfo.setText("");
                    if (contains(resp.getUser().getId())) {
                        Intent intent = new Intent(this, UserInfoActivity.class);
                        intent.putExtra("chatter", resp.getUser());
                        startActivity(intent);
                    }else {
                        Intent intent = new Intent(this, SearchResultActivity.class);
                        intent.putExtra("chatter", resp.getUser());
                        startActivity(intent);
                    }
                }
            }
        });
    }

    private boolean contains(int userId) {
        for (User user : SharedData.friendBeans) {
            if (user.getId() == userId)
                return true;
        }
        return false;
    }
}
